import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    meta: {title: '欢迎登陆'},
    component: () => import ('../views/login.vue')
  },
  {
    path: '/',
    component: () => import ('../components/Layout.vue'),
    children: [
      {
        path: '',
        component: () => import ('../views/Index.vue'),
        meta: {title: '首页'}
      },
      {
        path: 'menu',
        component: () => import ('../views/menu/index.vue'),
        meta: {title: '菜单'}
      },
      {
        path: 'role',
        component: () => import ('../views/role/index.vue'),
        meta: {title: '角色'}
      },
      {
        path: 'user',
        component: () => import ('../views/admin/index.vue'),
        meta: {title: '管理员'}
      },
      {
        path: 'category',
        component: () => import ('../views/category/index.vue'),
        meta: {title: '商品分类'}
      },
      {
        path: 'specs',
        component: () => import ('../views/specs/index.vue'),
        meta: {title: '商品规格'}
      },
      {
        path: 'goods',
        component: () => import ('../views/goods/index.vue'),
        meta: {title: '商品管理'}
      },
      {
        path: 'seckill',
        component: () => import ('../views/seckill/index.vue'),
        meta: {title: '商品秒杀'}
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  let userInfo = JSON.parse(localStorage.getItem('userInfo')) || {}
  document.title = to.meta.title;
  if(to.path === '/' || to.path === '/login') {
    // 首页和登录页，不校验
    next()
  }else {
    if(userInfo.token) {
      // 已登录
      next()
    }else {
      // 未登录
      next('/login')
    }
  }
})

export default router
